/**
 * volatile 引用类型（包括数组）只能保证引用本身的可见性，不能保证内部字段的可见性
 */
package com.mashibing.juc.c_012_Volatile;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class T03_VolatileReference2 {

    private static class Data {
//        int a, b;
        volatile int a;
        volatile int b;

        public Data(int a, int b) {
            this.a = a;
            this.b = b;
        }
    }

    volatile static Data data;

    public static void main(String[] args) throws IOException {

        Thread writer = new Thread(()->{
            for (int i = 0; i < 10000; i++) {
                data = new Data(i, i);
                try {
                    TimeUnit.MILLISECONDS.sleep(88);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread reader = new Thread(()->{
            while (data == null) {

            }
            int x = data.a;
            try {
                TimeUnit.MILLISECONDS.sleep(88);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int y = data.b;
            if(x != y) {
                System.out.printf("a = %s, b = %s \n", x, y);
            }
        });

        reader.start();
        writer.start();

        System.in.read();
    }
}
